﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.Exceptions;
using Autodesk.Revit.UI;
using YArchitech.Revit;

namespace YArchitech.HVAC
{
	[Transaction(TransactionMode.Manual)]
	public class CheckFourSprinkler : IExternalCommand
	{
		public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
		{
			Transaction transaction = null;
			Result result;
			try
			{
				if (commandData == null)
				{
					throw new System.ArgumentNullException();
				}
				UIDocument activeUIDocument = commandData.Application.ActiveUIDocument;
				Document document = activeUIDocument.Document;
				if (!YJKRevitTools.ViewCheck(activeUIDocument, new List<ViewType>
				{
					(ViewType)1,
					(ViewType)2
				}))
				{
					result = Autodesk.Revit.UI.Result.Cancelled;
				}
				else
				{
					transaction = new Transaction(document, "校核四喷头");
					transaction.Start();
					FrmCheckFourSprinkler frmCheckFourSprinkler = new FrmCheckFourSprinkler(activeUIDocument);
					frmCheckFourSprinkler.GetFourSprinklerFlow();
					DialogResult dialogResult;
					for (;;)
					{
						dialogResult = frmCheckFourSprinkler.ShowDialog();
						if (dialogResult != DialogResult.Abort)
						{
							break;
						}
						if (frmCheckFourSprinkler.iParam == 0)
						{
							frmCheckFourSprinkler.GetFourSprinklerFlow();
						}
						if (frmCheckFourSprinkler.iParam == 1)
						{
							frmCheckFourSprinkler.GetProtectArea();
						}
					}
					if (dialogResult != DialogResult.OK)
					{
						result = Autodesk.Revit.UI.Result.Succeeded;
					}
					else
					{
						transaction.Commit();
						result = Autodesk.Revit.UI.Result.Succeeded;
					}
				}
			}
			catch (Autodesk.Revit.Exceptions.OperationCanceledException)
			{
				result = Autodesk.Revit.UI.Result.Succeeded;
			}
			catch (Exception ex)
			{
				message = ex.Message;
				result = Autodesk.Revit.UI.Result.Failed;
			}
			finally
			{
				if (transaction != null)
				{
					TransactionStatus status = transaction.GetStatus();
					if ((int)status == 1)
					{
						transaction.Commit();
					}
					else if ((int)status == 5)
					{
						transaction.RollBack();
					}
				}
			}
			return result;
		}
	}
}
